package com.lunz.securityproject.util;

import com.alibaba.fastjson.JSON;
import com.lunz.securityproject.entity.vo.Vaptcha;
import com.lunz.securityproject.entity.vo.VaptchaResult;
import org.apache.commons.codec.Charsets;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author 施瑞贤
 * @email shiruixian@zhongruigroup.com
 * @date 2021/11/8 17:12
 */
@Component
public class VaptchaUtil {
    public static Integer postJSON(String url, String token) throws Exception{
        Vaptcha v = new Vaptcha();
        v.setId("61137f3cc108cd3a30dddf5c");
        v.setSecretkey("dc58db9aec9f4df5b728d06bdae18112");
        v.setScene(1);
        v.setIp("127.0.0.1");
        v.setToken(token);
        String json = JSON.toJSONString(v);
        StringEntity entity = new StringEntity(json, Charsets.UTF_8);
        String j = postRequest(url, entity);
        VaptchaResult vr = JSON.parseObject(j,VaptchaResult.class);
        return vr.getSuccess();
    }
    // 发送POST请求
    private static String postRequest(String url, HttpEntity entity) throws Exception {
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", "application/json");
        post.addHeader("Accept", "application/json");
        post.setEntity(entity);
        try {
            CloseableHttpClient client = HttpClientBuilder.create().build();
            HttpResponse response = client.execute(post);
            int code = response.getStatusLine().getStatusCode();
            if (code >= 400) {
                throw new Exception(EntityUtils.toString(response.getEntity()));
            }
            return EntityUtils.toString(response.getEntity());
        } catch (ClientProtocolException e) {
            throw new Exception("postRequest -- Client protocol exception!", e);
        } catch (IOException e) {
            throw new Exception("postRequest -- IO error!", e);
        } finally {
            post.releaseConnection();
        }
    }
}
